<template>
  <div class="space-y-6">
    <!-- 搜索和添加区域 -->
    <div class="flex justify-between">
      <div class="flex gap-4">
        <a-input-search
          v-model="searchParams.keyword"
          placeholder="请输入设备编号或名称搜索"
          style="width: 200px"
          @search="handleSearch"
          allow-clear
        />
        <a-select
          v-model="searchParams.categoryId"
          placeholder="请选择设备类型"
          style="width: 200px"
          @change="handleSearch"
          allow-clear
        >
          <a-option v-for="category in categories" :key="category.categoryId" :value="category.categoryId">
            {{ category.name }}
          </a-option>
        </a-select>
        <a-select
          v-model="searchParams.status"
          placeholder="请选择设备状态"
          style="width: 200px"
          @change="handleSearch"
          allow-clear
        >
          <a-option value="IDLE">空闲中</a-option>
          <a-option value="IN_USE">使用中</a-option>
          <a-option value="REPAIRING">维修中</a-option>
          <a-option value="SCRAPPED">已报废</a-option>
        </a-select>
      </div>
      <a-button type="primary" @click="openAddModal">
        <template #icon><icon-plus /></template>
        添加设备
      </a-button>
    </div>

    <!-- 设备列表表格 -->
    <a-table
      :data="tableData"
      :loading="loading"
      :pagination="pagination"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      stripe
    >
      <template #columns>
        <a-table-column title="设备编号" data-index="code" />
        <a-table-column title="设备名称" data-index="name" />
        <a-table-column title="设备类型" data-index="categoryName" />
        <a-table-column title="品牌" data-index="brand" />
        <a-table-column title="型号" data-index="model" />
        <a-table-column title="设备价值" data-index="value">
          <template #cell="{ record }">
            {{ record.value ? `¥${record.value.toFixed(2)}` : '-' }}
          </template>
        </a-table-column>
        <a-table-column title="规格" data-index="specifications" />
        <a-table-column title="位置" data-index="location" />
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="200" fixed="right">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" size="small" @click="editEquipment(record)">
                <template #icon><icon-edit /></template>
                编辑
              </a-button>
              <a-popconfirm
                content="确定要删除该设备吗？"
                @ok="deleteEquipment(record)"
              >
                <a-button type="text" status="danger" size="small">
                  <template #icon><icon-delete /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 添加/编辑设备弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="isEdit ? updateFormData : createFormData"
        :rules="rules"
        label-align="right"
        :style="{ width: '600px' }"
      >
        <template v-if="!isEdit">
          <a-form-item field="code" label="设备编号" :rules="[{required: true, message: '请输入设备编号'}]">
            <a-input v-model="createFormData.code" placeholder="请输入设备编号" />
          </a-form-item>
          <a-form-item field="categoryId" label="设备类型" :rules="[{required: true, message: '请选择设备类型'}]">
            <a-select v-model="createFormData.categoryId" placeholder="请选择设备类型">
              <a-option v-for="category in categories" :key="category.categoryId" :value="category.categoryId">
                {{ category.name }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="brand" label="品牌">
            <a-input v-model="createFormData.brand" placeholder="请输入品牌" />
          </a-form-item>
          <a-form-item field="model" label="型号">
            <a-input v-model="createFormData.model" placeholder="请输入型号" />
          </a-form-item>
          <a-form-item field="value" label="设备价值">
            <a-input-number
              v-model="createFormData.value"
              placeholder="请输入设备价值"
              :precision="2"
              :min="0"
              :step="1000"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item field="supplier" label="供应商">
            <a-input v-model="createFormData.supplier" placeholder="请输入供应商" />
          </a-form-item>
          <a-form-item field="purchaseDate" label="购买日期">
            <a-date-picker
              v-model="createFormData.purchaseDate"
              style="width: 100%"
              show-time
            />
          </a-form-item>
          <a-form-item field="warrantyPeriod" label="保修期">
            <a-date-picker
              v-model="createFormData.warrantyPeriod"
              style="width: 100%"
              show-time
            />
          </a-form-item>
        </template>
        
        <a-form-item field="name" label="设备名称" :rules="[{required: true, message: '请输入设备名称'}]">
          <a-input v-model="(isEdit ? updateFormData : createFormData).name" placeholder="请输入设备名称" />
        </a-form-item>
        <a-form-item field="specifications" label="规格">
          <a-input v-model="(isEdit ? updateFormData : createFormData).specifications" placeholder="请输入规格" />
        </a-form-item>
        <a-form-item field="location" label="位置">
          <a-input v-model="(isEdit ? updateFormData : createFormData).location" placeholder="请输入位置" />
        </a-form-item>
        
        <template v-if="isEdit">
          <a-form-item field="status" label="设备状态" :rules="[{required: true, message: '请选择设备状态'}]">
            <a-select v-model="updateFormData.status" placeholder="请选择设备状态">
              <a-option value="IDLE">空闲中</a-option>
              <a-option value="IN_USE">使用中</a-option>
              <a-option value="REPAIRING">维修中</a-option>
              <a-option value="SCRAPPED">已报废</a-option>
            </a-select>
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { 
  IconPlus, 
  IconEdit, 
  IconDelete
} from '@arco-design/web-vue/es/icon'
import type { 
  EquipmentVO, 
  EquipmentStatus, 
  EquipmentCategory, 
  EquipmentCreateDTO,
  EquipmentUpdateDTO,
  EquipmentQuery
} from '@/types/device'
import { getEquipmentList, createEquipment, updateEquipment } from '@/services/equipment'
import { getCategoryList } from '@/services/deviceCategory'

// 搜索参数
const searchParams = reactive<Partial<EquipmentQuery>>({
  keyword: undefined,
  categoryId: undefined,
  status: undefined,
  page: 1,
  size: 10
})

// 表格相关
const loading = ref(false)
const tableData = ref<EquipmentVO[]>([])
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
})

// 设备分类列表
const categories = ref<EquipmentCategory[]>([])

// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加设备')
const formRef = ref()
const isEdit = ref(false)

// 创建设备的表单数据
const createFormData = reactive<EquipmentCreateDTO>({
  code: '',
  name: '',
  categoryId: 0,
  brand: '',
  model: '',
  value: undefined,
  specifications: '',
  location: '',
  supplier: '',
  purchaseDate: '',
  warrantyPeriod: '',
})

// 编辑设备的表单数据
const updateFormData = reactive<EquipmentUpdateDTO>({
  equipmentId: 0,
  name: '',
  location: '',
  specifications: '',
  status: 'IDLE' as EquipmentStatus
})

// 获取设备分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryList({ page: 1, size: 100 })
    console.log('设备分类响应数据:', res)
    
    const { data: response } = res
    if (response.code === 1 && response.data && Array.isArray(response.data.records)) {
      categories.value = response.data.records
    } else {
      console.error('返回的分类记录格式错误:', response)
      Message.error('分类数据格式错误')
    }
  } catch (error) {
    console.error('获取设备分类失败:', error)
    Message.error('获取设备分类失败')
  }
}

// 获取设备列表
const fetchEquipmentList = async () => {
  loading.value = true
  try {
    const res = await getEquipmentList({
      page: pagination.current,
      size: pagination.pageSize,
      keyword: searchParams.keyword || undefined,
      categoryId: searchParams.categoryId || undefined,
      status: searchParams.status || undefined
    })
    console.log('设备列表响应数据:', res)
    
    const { data: response } = res
    if (response.code === 1 && response.data && Array.isArray(response.data.records)) {
      tableData.value = response.data.records
      pagination.total = response.data.total || 0
    } else {
      console.error('返回的记录格式错误:', response)
      Message.error('数据格式错误')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    Message.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  // 过滤空值
  const params = {
    ...searchParams,
    page: pagination.current,
    size: pagination.pageSize,
    keyword: searchParams.keyword || undefined,
    categoryId: searchParams.categoryId || undefined,
    status: searchParams.status || undefined
  }
  // 获取设备列表
  fetchEquipmentList()
}

// 分页
const onPageChange = (page: number) => {
  pagination.current = page
  fetchEquipmentList()
}

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchEquipmentList()
}

// 设备状态工具函数
const getStatusLabel = (status: EquipmentStatus) => {
  const statusMap: Record<EquipmentStatus, string> = {
    'IDLE': '空闲中',
    'IN_USE': '使用中',
    'REPAIRING': '维修中',
    'SCRAPPED': '已报废'
  }
  return statusMap[status] || '未知状态'
}

const getStatusColor = (status: EquipmentStatus) => {
  const colorMap: Record<EquipmentStatus, string> = {
    'IDLE': 'green',
    'IN_USE': 'blue',
    'REPAIRING': 'orange',
    'SCRAPPED': 'red'
  }
  return colorMap[status] || 'default'
}

// 添加设备
const openAddModal = () => {
  isEdit.value = false
  modalTitle.value = '添加设备'
  modalVisible.value = true
  Object.assign(createFormData, {
    code: '',
    name: '',
    categoryId: 0,
    brand: '',
    model: '',
    value: undefined,
    specifications: '',
    location: '',
    supplier: '',
    purchaseDate: '',
    warrantyPeriod: '',
  })
}

// 编辑设备
const editEquipment = (record: EquipmentVO) => {
  isEdit.value = true
  modalTitle.value = '编辑设备'
  modalVisible.value = true
  Object.assign(updateFormData, {
    equipmentId: record.equipmentId,
    name: record.name,
    location: record.location,
    specifications: record.specifications,
    status: record.status
  })
}

// 删除设备
const deleteEquipment = async (record: EquipmentVO) => {
  try {
    // TODO: 实现删除设备的API
    Message.success('删除成功')
    fetchEquipmentList()
  } catch (error) {
    Message.error('删除失败')
  }
}

// 提交表单
const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    if (isEdit.value) {
      const res = await updateEquipment(updateFormData.equipmentId, updateFormData)
      console.log('更新设备响应:', res)
      
      if (res.status === 200 && res.data.code === 1) {
        Message.success('更新成功')
        modalVisible.value = false
        fetchEquipmentList()
      } else {
        Message.error(res.data.msg || '更新失败')
      }
    } else {
      // 格式化日期
      const formattedData = {
        ...createFormData,
        purchaseDate: createFormData.purchaseDate ? new Date(createFormData.purchaseDate).toISOString() : undefined,
        warrantyPeriod: createFormData.warrantyPeriod ? new Date(createFormData.warrantyPeriod).toISOString() : undefined
      }
      const res = await createEquipment(formattedData)
      console.log('创建设备响应:', res)
      
      if (res.status === 200 && res.data.code === 1) {
        Message.success('添加成功')
        modalVisible.value = false
        fetchEquipmentList()
      } else {
        Message.error(res.data.msg || '添加失败')
      }
    }
  } catch (error) {
    console.error('表单提交错误:', error)
    Message.error('表单提交失败')
  }
}

const handleModalCancel = () => {
  formRef.value.resetFields()
  modalVisible.value = false
}

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入设备编号' }],
  name: [{ required: true, message: '请输入设备名称' }],
  categoryId: [{ required: true, message: '请选择设备类型' }],
  status: [{ required: true, message: '请选择设备状态' }]
}

onMounted(() => {
  fetchCategories()
  fetchEquipmentList()
})

defineExpose({
  handleSearch,
  onPageChange,
  onPageSizeChange,
  getStatusLabel,
  getStatusColor,
  openAddModal,
  editEquipment,
  deleteEquipment,
  handleModalOk,
  handleModalCancel
})
</script> 